package com.yt.phone.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.phone.models.bo.BillSaveBO;
import com.yt.phone.models.dto.BillDTO;
import com.yt.phone.models.vo.BillVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.phone.models.service.IBillService;
import com.yt.phone.models.bo.BillBO;
import com.yt.phone.models.dto.BillDTO;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 账单信息控制器
 *
 * @author lizicong
 * @Date 2025-11-05 23:40:06
 */

@RestController
@RequestMapping("/api/bill")
@Slf4j
@Api(value = "BillApiController",tags = "账单信息Api接口")
public class BillApiController {

    @DubboReference
    private IBillService billService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<BillDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        BillDTO dto = billService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "账单信息列表",notes = "账单信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<BillDTO>> queryPageList(BillBO bo){
        Wrapper<BillDTO> wrapper = new EntityWrapper<>();
        if (bo.getStatus() != null){
            wrapper.eq("status", bo.getStatus());
        }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<BillDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = billService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    @ApiOperation(value = "添加账单信息",notes = "添加账单信息")
    @PostMapping(value = "/insert")
    public Result insert(@RequestBody BillSaveBO saveBO) {
        boolean flag = billService.add(saveBO);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    @ApiOperation(value = "修改账单信息",notes = "修改账单信息")
    @PostMapping("/update")
    public Result update(@RequestBody BillSaveBO saveBO){
        BillDTO dto = new BillDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setBillId(saveBO.getBillId());
        boolean flag = billService.updateById(dto);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @ApiOperation(value = "删除账单信息",notes = "删除账单信息")
    @ApiImplicitParam(name = "id",value = "账单信息id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        boolean flag = billService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @ApiOperation(value = "获取账单信息列表",notes = "获取账单信息列表")
    @PostMapping("/list")
    public Result<List<BillDTO>> getbillList(){
        System.out.println("获取列表检测点");
        List<BillDTO> list = billService.getbillList();
        return new Result<>(list);
    }

    @ApiOperation(value = "获取账单信息分页列表", notes = "获取账单信息分页列表")
    @PostMapping("/pagelist/{page}/{keyword:.*}")
    public Result<Map<String, Object>> getbillListpage(@PathVariable("page") int page,@PathVariable(value = "keyword", required = false) String keyword) {
        //参数校验
        if (page < 1) {
            log.warn("请求页码不合法：{}，自动修正为1", page);
            page = 1;
        }

        System.out.println(keyword+"----------------------");

        // 处理keyword为null的情况（默认为空字符串，避免后续判断null）
        if (keyword == null || keyword.equalsIgnoreCase("***")) {
            keyword = "";
        }
        // 限制keyword长度（避免超长字符串导致的问题，根据业务调整长度）
        if (keyword.length() > 50) {
            keyword = keyword.substring(0, 50);
            log.warn("搜索关键词过长，已截断为：{}", keyword);
        }
        log.info("获取分页账单信息列表，页码：{},关键字：{}", page,keyword);

        // 1. 调用 Service 获取分页数据
        Page<BillVO> billDTOPage = billService.getpagebillList(page,keyword);

        // 2. 生成页码列表
        int pages = (int) billDTOPage.getPages();
        List<Integer> pageList = IntStream.rangeClosed(1, pages)
                .boxed()
                .collect(Collectors.toList());

        // 3. 用 Map 封装所有信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("records", billDTOPage.getRecords()); // 当前页数据
        resultMap.put("current", billDTOPage.getCurrent()); // 当前页码
        resultMap.put("size", billDTOPage.getSize()); // 每页条数
        resultMap.put("total", billDTOPage.getTotal()); // 总记录数
        resultMap.put("pages", pages); // 总页数
        resultMap.put("pageList", pageList); // 页码列表

        return new Result<>(resultMap);
    }

    @ApiOperation(value = "根据关键词获取账单信息列表",notes = "根据关键词获取账单信息列表")
    @PostMapping("/search/{keyword}")
    public Result<List<BillDTO>> searchgetbillList(@PathVariable("keyword") String keyword){
        System.out.println("获取列表检测点");
        List<BillDTO> list = billService.searchgetbillList(keyword);
        return new Result<>(list);
    }
    //获取当前用户id的订单列表
    @ApiOperation(value = "获取当前用户id的订单列表",notes = "获取当前用户id的订单列表")
    @PostMapping("/getBillListByUserId/{userId}")
    public Result<List<BillDTO>> getBillListByUserId(@PathVariable("userId") Long userId){
        System.out.println("获取列表检测点");
        List<BillDTO> list = billService.getBillListByUserId(userId);
        return new Result<>(list);
    }
}
